<template>
  <div class="checkout">
    <div class="mask"></div>
    <div class="checkoutMain">
      <div>
        <p>结账</p>
        <i class="el-icon-close" @click="accountsCloseIconClick"></i>
      </div>
      <div class="money">
        <span>
          <p class="blue">{{ yingshou_jiner ? yingshou_jiner : 0 }}</p>
          <p>应付总额</p>
        </span>
        <span>
          <!-- <p>{{ yingshou_jiner - totalPaid }}</p> -->
          <p>{{ notPayTotal }}</p>
          <p>未付总额</p>
        </span>
        <span>
          <!-- <p>{{ payInputValue ? payInputValue : 0 }}</p>
          <p>已付总额</p> -->
          <p>{{ totalPaid }}</p>
          <p>已付总额</p>
        </span>
        <span>
          <p>{{ showCurrentVipObj.balance ? showCurrentVipObj.balance : 0 }}</p>
          <p>卡内余额</p>
        </span>
      </div>

      <div class="pay">
        <p>付款方式</p>
        <el-select
          class="w160"
          v-model="payMethodPullSelectValue"
          placeholder="请选择"
          @change="payMethodsPullSelectChange"
        >
          <el-option
            v-for="item in payMethodList"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
        <p>支付</p>
        <el-input
          class="w160"
          @keyup.enter.native="moneyEnter"
          type="number"
          v-model.number="payInputValue"
        ></el-input>
        <el-button type="primary" plain @click="continueBtnClick"
          >继续</el-button
        >
        <!-- <p>备注</p>
        <el-input class="w160"></el-input> -->
      </div>

      <!-- 表格区域 -->
      <div class="bottom_table_container">
        <div class="table_container">
          <!-- 左边样式 -->
          <div class="heard_wrap">
            <p class="one" style="background: #f8f8f8">付款方式</p>
            <p style="background: #f8f8f8">付款金额</p>
          </div>
          <!-- 支付样式 -->
          <div
            class="heard_wrap"
            v-for="(item, index) in SelectpayMethodList"
            :key="index"
          >
            <p class="one">{{ item.paymentName }}</p>
            <p>{{ item.paymentMoney }}</p>
          </div>
        </div>
        <!-- 右边样式 -->
        <div class="right_table_container">
          <div class="heard_wrap_right">
            <p class="one" style="background: #f8f8f8">积分</p>
            <p style="background: #f8f8f8">积分兑换</p>
          </div>
          <div class="jifeng_container">
            <p class="one">{{ duihuan_ji_fen_obj.integralNumber }}</p>
            <p>{{ duihuan_ji_fen_obj.exchangeIntegral }}</p>
          </div>
        </div>
      </div>

      <div class="btn">
        <el-button @click="clearEmptyBtnClick">清空</el-button>
        <el-button type="primary" @click="confirmBtnClick">确定</el-button>
      </div>
    </div>
    <!-- 密码弹出框 -->
    <div class="password_dialog_container">
      <el-dialog
        :visible.sync="isShowPassWordDialog"
        width="20%"
        top="30vh"
        :close-on-click-modal="false"
        :before-close="passwordCancleBtnClick"
      >
        <template #title> <span class="psw_title">密码验证</span> </template>
        <p style="margin-bottom: 10px; color: #000">请输入支付密码</p>
        <el-input v-model="passwordInputValue" type="password"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="passwordCancleBtnClick">取 消</el-button>
          <el-button type="primary" @click="psdConfrimBtnClick"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 密码接口  //
import { check_password_api } from '../../../../request/page_base_api/page_base_api'
// 接口的映入
import {
  accounts_confrim_api,
  pay_methods_api,
  get_ji_fen_duihuan_data_api
} from '../../../../request/store/store_sales_request.js'
export default {
  props: {
    // 销售序号
    sellSequence: {
      type: [String, Number],
      default: ''
    },
    // 整个页面选中的vip对象
    showCurrentVipObj: {
      type: Object,
      default() {
        return {}
      }
    },
    // 应付金额(不行就直接返回bigNumber的c)
    yingshou_jiner: {
      type: [String, Number, Object],
      default: 0
    }
  },
  data() {
    return {
      // 付款方式下拉框选中的值和数组
      payMethodPullSelectValue: '',
      payMethodList: [],
      // 支付输入框拿到的值
      payInputValue: '',
      // 付款表格的数组
      SelectpayMethodList: [],
      tempSelectpayMethodList: [],
      // 已付金额(在计)
      // payedMoney: 0,
      // 一积分能兑换多少钱的对象
      duihuan_ji_fen_obj: {},
      // 选中的对象，保存一个全局的支付方式的对象（选中之后，根据id找出来的对象）
      overallSelectPayObj: {},
      // 控制密码弹出框的显示和隐藏
      isShowPassWordDialog: false,
      // 密码弹出框输入的值
      passwordInputValue: '',
      // 定义一个全局的变量，来控制点击继续密码dialog的时候逻辑
      flag: true,
      id: null
    }
  },
  created() {
    // console.log(this.sellSequence, 'showCurrentVipObj')
    // console.log(this.showCurrentVipObj, 'showCurrentVipObj')
    this.pay_methods()
  },
  methods: {
    // 获取支付方式的接口
    async pay_methods() {
      const { data: res } = await pay_methods_api()
      console.log(res, 'pay_methods_api')
      this.payMethodList = res.data
    },
    /* 密码框取消的时候，触发的函数 */
    passwordCancleBtnClick() {
      this.isShowPassWordDialog = false
      this.flag = true
    },

    /*
      点击确认的时候触发的函数
    */
    async confirmBtnClick() {
      // console.log(this.SelectpayMethodList, 'SelectpayMethodList')
      //付款方式和付款金额不能为空
      if (!this.payMethodPullSelectValue || !this.payInputValue) {
        return this.$message.warning('付款方式 和 付款金额 不能为空')
      }
      if (!this.SelectpayMethodList.length) {
        return this.$message.warning('请点击 继续 ,再点击确认付款')
      }

      const { data: res } = await accounts_confrim_api(this.SelectpayMethodList)
      // console.log(res, 'accounts_confrim_api')
      if (res.code !== 200) return
      this.$message.success('结账成功')
      // 关闭dialog并且禁用结账按钮
      this.$emit('accountsCloseIconClickAndDiableBtn')
    },
    // 继续按钮被点击的时候，触发的函数
    async continueBtnClick() {
      // 没有输入直接return
      if (!this.payMethodPullSelectValue || !this.payInputValue) return
      // 如果选中余额抵扣就弹框要密码
      if (
        this.overallSelectPayObj.name === '余额抵扣' ||
        this.overallSelectPayObj.name === '积分兑换'
      ) {
        // 只弹起一次密码输入框
        if (this.flag) {
          this.isShowPassWordDialog = true
          this.flag = false
          return
        }
      }

      // 不是空对象，证明已经选择了积分兑换
      const keysList = Object.keys(this.duihuan_ji_fen_obj)
      if (keysList.length) {
        if (this.payInputValue > this.duihuan_ji_fen_obj.integralNumber) {
          this.$message.warning(
            `${this.payInputValue}积分超过最大积分${this.duihuan_ji_fen_obj.integralNumber}`
          )
          // 然后直接退出函数
          return
        }
        // 计算积分兑换后的钱数
        let disMoney =
          (this.payInputValue * this.duihuan_ji_fen_obj.exchangeIntegral) /
          this.duihuan_ji_fen_obj.integralNumber
        // 剩下的是没有超过的 //
        const obj = {
          paymentName: this.payMethodPullSelectValue,
          paymentMoney: disMoney,
          sellSequence: this.sellSequence,
          id: this.showCurrentVipObj.id,
          exchangeIntegral: this.payInputValue, // 积分数
          paymentNo: this.overallSelectPayObj.no // 付款编号代表付款方式
        }
        // 返回的不是-1,证明里面有，那么就应该删掉，并且push新的上去
        // （tongxia-----start-------）
        const hasIndex = this.SelectpayMethodList.findIndex((item) => {
          return item.paymentName === obj.paymentName
        })
        console.log('hasIndex', hasIndex)
        // 不等于-1，证明找到，先删了，然后再push进去，然后return
        if (hasIndex !== -1) {
          this.SelectpayMethodList.splice(hasIndex, 1)
          this.SelectpayMethodList.push(obj)
          return
        }
        // （tongxia-----end-------）// 当然可以封装方法
        // 没有找到直接push进去
        this.SelectpayMethodList.push(obj)
        // 选择积分兑换的话，执行到这里直接return
        //   this.tempSelectpayMethodList.push(obj)
        //   this.SelectpayMethodList.push(
        //     ...this.getNewGoodsList(this.tempSelectpayMethodList)
        //   )
        //   console.log(this.SelectpayMethodList, '333333333')
        return
      }
      // -----------------------选择其他方式付款（选中现金付款的方式）-----------------------------
      // 拼接对象push到SelectpayMethodList 选择方式表格中，没有发ajax
      const obj = {
        paymentName: this.payMethodPullSelectValue,
        paymentMoney: this.payInputValue,
        sellSequence: this.sellSequence,
        id: this.showCurrentVipObj.id,
        paymentNo: this.overallSelectPayObj.no
      }
      // （tongxia-----start-------）
      console.log('obj', obj)
      // 返回的不是-1,证明里面有，那么就应该删掉，并且push新的上去
      const hasIndex = this.SelectpayMethodList.findIndex((item) => {
        return item.paymentName === obj.paymentName
      })
      console.log('hasIndex', hasIndex)
      // 不等于-1，证明找到，先删了，然后再push进去，然后return
      if (hasIndex !== -1) {
        this.SelectpayMethodList.splice(hasIndex, 1)
        this.SelectpayMethodList.push(obj)
        return
      }
      // （tongxia-----end-------）// 当然可以封装方法

      // 没有找到直接push进去
      this.SelectpayMethodList.push(obj)

      // this.tempSelectpayMethodList.push(obj)
      // this.SelectpayMethodList = this.getNewGoodsList(
      //   this.tempSelectpayMethodList
      // )
      // //   this.tempPyMethodsList.push(this.questData)
      // //   this.choosePayMethodsList = this.getNewGoodsList(this.tempPyMethodsList)
      // // // console.log(this.SelectpayMethodList, 'this.SelectpayMethodList')
      // // console.log(
      // //   this.getNewGoodsList(this.tempSelectpayMethodList),
      // //   '11111111111'
      // // )
    },
    // 关闭ICon被点击的时候。触发的函数
    accountsCloseIconClick() {
      this.$emit('accountsCloseIconClick')
    },
    // 付款方式选择改变的时候，触发的函数
    async payMethodsPullSelectChange(val) {
      // 选中的对象，保存一个全局的支付方式的对象
      this.overallSelectPayObj = this.payMethodList.find((item) => {
        return item.name === val
      })
      // console.log(this.overallSelectPayObj, 'overallSelectPayObj')
      // 这个是防止重复缓存积分对象
      if (val !== '积分兑换') {
        this.duihuan_ji_fen_obj = {}
      }
      if (val === '积分兑换') {
        const curentItem = this.payMethodList.find((item) => {
          return item.name === '积分兑换'
        })
        // console.log(curentItem, 'curentItem')
        // 这个是获取积分接口
        const { data: res } = await get_ji_fen_duihuan_data_api({
          paymentNo: curentItem.no,
          vip: this.showCurrentVipObj.phone
        })
        // console.log(res, 'get_ji_fen_duihuan_data_api')
        // 拿到一积分能兑换多少钱
        this.duihuan_ji_fen_obj = res.data
      }
    },
    // 支付输入框按下回车的时候，触发的函数
    moneyEnter() {
      // 如果选中余额抵扣就弹框要密码
      if (this.overallSelectPayObj.name === '余额抵扣') {
        this.isShowPassWordDialog = true
      }
    },
    // 清空按钮被点击的时候，触发的函数
    clearEmptyBtnClick() {
      // 重置
      console.log('点击了重置按钮')
      this.SelectpayMethodList = []
      this.duihuan_ji_fen_obj = {}
      this.totalPaid = 0
      this.payMethodPullSelectValue = ''
      this.payInputValue = ''
    },
    // 密码输入框中的确认被点击的时候，触发的函数
    async psdConfrimBtnClick() {
      // console.log(this.showCurrentVipObj)
      // 先采用md5加密
      const jiami_pay = this.$md5(
        `${this.showCurrentVipObj.phone}:${this.passwordInputValue}`
      )

      // 加密的字符串
      const jia_mi_psw = {
        phone: this.showCurrentVipObj.phone,
        pass: jiami_pay
      }
      // 请求加密的接口
      const { data: res } = await check_password_api(jia_mi_psw)
      // console.log('res', res)
      if (!res.data) {
        return this.$message.warning('密码不正确')
      }
      // 密码正确
      this.$message({
        type: 'success',
        message: '密码正确',
        duration: 1000
      })
      /* 密码输入正确之后，直接push到表格，不用点击继续才能点确认 */
      const obj = {
        paymentName: this.payMethodPullSelectValue,
        paymentMoney: this.payInputValue,
        sellSequence: this.sellSequence,
        id: this.showCurrentVipObj.id,
        paymentNo: this.overallSelectPayObj.no
      }
      // console.log('不用点击继续才能点确认', obj)
      this.SelectpayMethodList.push(obj)
      // this.continueBtnClick()
      // this.tempSelectpayMethodList.push(obj)
      // this.SelectpayMethodList = this.getNewGoodsList(
      //   this.tempSelectpayMethodList
      // )

      // 关闭密码对话框
      this.isShowPassWordDialog = false
    }

    // getNewGoodsList(params) {
    //   let temp = {}
    //   for (let i in params) {
    //     let key = params[i].id //判断依据
    //     if (temp[key]) {
    //       // 旧数据
    //       temp[key].id = params[i].id
    //       temp[key].paymentMoney = params[i].paymentMoney //相加值
    //       temp[key].paymentName = params[i].paymentName
    //       temp[key].paymentNo = params[i].paymentNo
    //       temp[key].sellSequence = params[i].sellSequence
    //     } else {
    //       // 新数据
    //       temp[key] = {}
    //       temp[key].id = params[i].id
    //       temp[key].paymentMoney = params[i].paymentMoney
    //       temp[key].paymentName = params[i].paymentName
    //       temp[key].paymentNo = params[i].paymentNo
    //       temp[key].sellSequence = params[i].sellSequence
    //     }
    //   }
    //   let newArry = []
    //   for (let k in temp) {
    //     newArry.push(temp[k])
    //   }
    //   return newArry
    // }
  },
  computed: {
    // 已付总额
    // totalPaid() {
    //   return this.SelectpayMethodList.reduce((pre, item) => {
    //     return pre + item.paymentMoney
    //   }, 0)
    // },
    // 已付总额
    totalPaid: {
      get() {
        return this.SelectpayMethodList.reduce((pre, item) => {
          // return pre + item.paymentMoney // js计算精度有问题，用了大数字的插件
          // 大数字的加法
          return new this.$bigNumber(pre).plus(item.paymentMoney)
        }, 0)
      },

      set() {}
    },
    // 未付总额
    notPayTotal: {
      get() {
        // 大数字的减法
        return new this.$bigNumber(this.yingshou_jiner).minus(this.totalPaid)
      },
      set() {}
    }
  }
}
</script>

<style lang="less" scoped>
//
.bottom_table_container {
  height: 250px;
  overflow: auto;
}
// 密码dialog样式
.password_dialog_container {
  //输入框的样式
  // input输入框的样式
  /deep/.el-input {
    // 宽度生效
    width: 100%;
    height: 32px;
    .el-input__inner {
      height: 32px;
    }
  }
  /deep/.el-dialog__header {
    display: flex;
    align-items: center;
    font-weight: 800;
    padding-left: 10px !important;
    padding: 0;
    background: #f2f5fa;
    height: 40px;
    .el-dialog__headerbtn {
      top: 11px;
      right: 14px;
    }
  }
}
.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  z-index: 99;
}
.checkoutMain {
  position: fixed;
  top: 20%;
  left: 50%;
  transform: translateX(-50%);
  width: 700px;
  z-index: 99;
  background-color: white;
  overflow: auto;
  padding-bottom: 1.5vh;
}
.checkoutMain > div:first-child {
  justify-content: space-between;
  padding: 10px 15px;
  background: #f4f4f4;
  font-weight: 700;
}

p {
  white-space: nowrap;
}
.checkoutMain > div {
  display: flex;
}

.checkoutMain > div:not(:first-child) {
  margin: 1.5vh 1vw 0;
}
.money {
  background: #f2f5fa;
  border-radius: 5px;
  padding: 1.5vh 1vw;
}
.money span {
  flex-grow: 1;
  text-align: center;
}
.money p:first-child {
  font-size: 2.5vh;
}

.pay p {
  margin-right: 0.5vw;
}

.table > div {
  display: flex;
  text-align: center;
}
.table > div:first-child {
  margin-right: 1vw;
}
.table div {
  flex-grow: 1;
}
.table p {
  border: 1px solid #f0f0f0;
  line-height: 4vh;
}
.table p:first-child {
  border-bottom: none;
  background: #f8f8f8;
  font-weight: bolder;
}

.btn {
  float: right;
}

.w160 {
  width: 160px;
  margin-right: 0.5vw;
}

.blue {
  color: #409eff;
}
</style>

<style lang="less">
.checkoutMain .el-input__inner {
  height: 30px !important;
}
.checkoutMain .el-input__icon {
  line-height: 30px !important;
}

// 支付样式
.heard_wrap {
  border: 1px solid #f2f5fa;
  width: 300px;
  display: flex;
  justify-content: space-around;
  p {
    width: 150px;
    height: 50px;
    text-align: center;
    line-height: 50px;
    margin: 0;
  }
  .one {
    border-right: 2px solid #f2f5fa;
  }
}
.table_container {
  display: flex;
  flex-direction: column;
}
// 右边
.heard_wrap_right {
  border: 1px solid #f2f5fa;
  width: 300px;
  display: flex;
  justify-content: space-around;
  p {
    width: 150px;
    text-align: center;
    line-height: 50px;
    margin: 0;
    height: 50px;
  }
  .one {
    border-right: 2px solid #f2f5fa;
  }
}

.right_table_container {
  margin-left: 30px;
  display: flex;
  flex-direction: column;
  .jifeng_container {
    display: flex;
    justify-content: space-around;
    height: 50px;
    border: 1px solid #f2f5fa;
    align-items: center;
  }
}
</style>
